// pages/article/article.js
var app = getApp();
let innerAudioContext = null;
Page({
  /**
	 * 页面的初始数据
	 */
  data: {
    kFootshow: true,
    active: "0",
    id: "",
    banner: "",
    title: "",
    datas: [],
    categories: [],
    loading: false,
    allLoaded: false,
    goload: true,
    isLoadMore: true,
    page: 1,
    total_page: 0,
    show1: false,
    noNotice: false,
    article_pay:'',

    searchText:'',
    playInd:null,
    // 开始播放请求接口
    postStart: false,
    sliderShow:false,
  },

  /**
	 * 生命周期函数--监听页面加载
	 */
  onLoad: function(options) {
    if (options.id) {
      this.setData({
        id: options.id,
      });
    }
    this.setData({
      options
    })
    
    this.initData();
    innerAudioContext = wx.createInnerAudioContext();

    //获取数据
    // this.getNetData();
  },
  /**
	 * 生命周期函数--监听页面初次渲染完成
	 */
  onReady: function() {

  },

  /**
	 * 生命周期函数--监听页面显示
	 */
  onShow: function() {
    //获取数据
    this.getNetData();
    this.init();
  },
  async startPlayOrPause(e){
    let item = e.currentTarget.dataset.item;
    if(item.has_one_article_pay){
      if(!item.has_one_record){
        wx.navigateTo({
          url: '/packageD/article/articleList/articleList?article_id=' + item.id
        });
        return
      }
    }
    let check = await this.checkPrivilege(item.id);
    console.log(check)
    if(check.result == 0){
      wx.showToast({
        title: check.msg,
        icon:'none',
        duration:1000
      })
      return
    }else{
      let i = e.currentTarget.dataset.i;
      if(!this.data.sliderShow ) this.setData({sliderShow : true})
      if (this.data.playInd != i) {
        innerAudioContext.stop();
        this.data.postStart = false;
      }
      for(let k = 0;k<this.data.datas.length;k++){
        if(k == i){
          this.data.datas[k].playStatus = true;
          innerAudioContext.src = encodeURI(item.audio_link);
          innerAudioContext.play();
        }else{
          this.data.datas[k].playStatus = false
        }
      }
      this.setData({
        playInd:i,
        datas:this.data.datas
      })
    }
  },
  checkPrivilege(id){
    return new Promise((resolve, reject)=>{
      let urlStr = app.getNetAddresss("plugin.article.api.article.get-article");
      app._getNetWork({
        url: urlStr,
        data: {
          article_id:id
        },
        success: (resdata) => {
          var res = resdata.data;
          if (res.result == 1) {
            resolve(res)
          }else{
            resolve(res)
          }
        },
        fail: function (res) {
          console.log(res);
        }
      });
    })
  },
  init() {
    innerAudioContext.onCanplay(() => {});
    innerAudioContext.onPlay(() => {
      console.log("开始播放");
      console.log(innerAudioContext.duration);
      this.startPostMethod()
    });
    innerAudioContext.onTimeUpdate(() => {
      setTimeout(() => {
        let smun = (innerAudioContext.currentTime / innerAudioContext.duration) * 100;
        var valueSlmin = parseInt(smun);
        this.setData({
          // currentTime: this.realFormatSecond(innerAudioContext.duration),
          // slmin: this.realFormatSecond(innerAudioContext.currentTime),
          valueSlmin: valueSlmin,
          audio_length: innerAudioContext.duration,
        });
      }, 500);
    });
    innerAudioContext.onEnded((e)=>{
      this.data.datas[this.data.playInd].playStatus = false;
      this.setData({
        datas:this.data.datas
      })
      this.data.postStart = false;
    })
    innerAudioContext.onError((res) => {
      // wx.showToast({
      //   title: "播放错误",
      //   icon: "none",
      // });
    });
  },
  startPostMethod() {
    if (this.data.postStart == false) {
      let urlStr = app.getNetAddresss("plugin.article.api.article.clickAudioViews");
      app._getNetWork({
        url: urlStr,
        data: {
          article_id:this.data.datas[this.data.playInd].id
        },
        success: (resdata) => {
          var res = resdata.data;
          if (res.result == 1) {
            console.log(this.data.datas[this.data.playInd])
            this.data.datas[this.data.playInd].virtual_audio_views = res.data.virtual_audio_views;
            this.setData({
              datas:this.data.datas
            })
          }
        },
        fail: function (res) {
          console.log(res);
        }
      });
    } else {
      console.log('暂停过 postStart = true')
    }
  },
  pause(e){
    let i = e.currentTarget.dataset.i;
    this.data.datas[i].playStatus = false;
    this.data.postStart = true;
    this.setData({
      datas:this.data.datas
    })
    innerAudioContext.pause();
  },
  tapClose(){
    this.setData({
      sliderShow: false
    })
  },
  sildein(e) {
    var setvalue = e.detail.value / 100;
    var long = this.data.audio_length * setvalue;
    this.data.datas[this.data.playInd].playStatus = false;
    this.setData({
      datas:this.data.datas
    })
    innerAudioContext.seek(long);
    innerAudioContext.play();
  },
  changeSilde(e){
    let setvalue = e.detail;
    let long = this.data.audio_length * (setvalue / 100);
    this.data.datas[this.data.playInd].playStatus = true;
    this.setData({
      datas:this.data.datas
    })
    innerAudioContext.seek(long);
    innerAudioContext.play();
  },
  /**
	 * 生命周期函数--监听页面隐藏
	 */
  onHide: function() {
    innerAudioContext.stop();
    innerAudioContext.destroy();
  },

  /**
	 * 生命周期函数--监听页面卸载
	 */
  onUnload: function() {
		innerAudioContext.stop();
    innerAudioContext.destroy();
  },

  /**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
  onPullDownRefresh: function() {
    this.initData();
    //获取数据
    this.getNetData();
  },

  /**
	 * 页面上拉触底事件的处理函数
	 */
  onReachBottom: function() {
    // 加载更多
    if (this.data.isLoadMore) {
      this.getMoreData();
    } else {
      console.log('没有更多数据');
    }
  },
  shareTap(e){
    console.log(e)
  },
  /**
	 * 用户点击右上角分享
	 */
  onShareAppMessage: function(e) {
    if(e.target.dataset.item && e.target && e){
      let item = e.target.dataset.item;
      let shareJson = {
        title:item.title,
        id:item.id,
        img:item.thumb
      }
      let json = {
        title:shareJson.title,
        path:`/packageA/member/course/VoiceDetail/VoiceDetail?article_id=${shareJson.id}`,
        imageUrl:shareJson.img
      }
      if(this.data.options.taskID){
        json.path += `&taskID=${this.data.options.taskID}&taskDay=${this.data.options.taskDay}&task_type=article`
      }
      if(shareJson){
        return json
      }
    }
  },
  onShareTimeline(){},
  tabrshowbtn(e) {
    let bol = e.detail;
    if (bol) {
      this.setData({
        kFootshow: false
      });
    }
  },
  initData() {
    if (innerAudioContext) {
      innerAudioContext.stop();
    }
    this.setData({
      page: 1,
      total_page: 0,
      goload: true,
      loading: true,
      allLoaded: false,
      isLoadMore: true,
      datas: [],
      sliderShow:false
    });
  },
  handSearch(){
    this.initData();
    //获取数据
    this.getNetData();
  },
  //获取数据
  getNetData() {
    let that = this;
    let json = {
      category_id: this.data.id,
      page: 1,
      keyword: this.data.searchText,
    };
    let urlStr = app.getNetAddresss("plugin.article.api.article.get-articles");
    app._getNetWork({
      url: urlStr,
      data: json,
      success: function(resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            noNotice: false,
            total_page: res.data.articles.last_page,
            article_pay:res.data.article_pay
          });
          if (!that.data.total_page) {
            that.setData({
              total_page: 0
            });
          }
          if (res.data.categories.length <= 0) {
            that.setData({
              noNotice: true
            });
          }
          that.setData({
            title: res.data.title,
            datas: res.data.articles.data,
            categories: res.data.categories
          });
          console.log(that.data.datas);
          if(that.data.id){
            that.data.categories.forEach((item,index,key)=>{
              if(item.id==that.data.id){
                that.setData({
                  active:index+1
                });
              }
            });
          }
          wx.setNavigationBarTitle({
            title: res.data.title
          });
        } else {
          that.setData({
            noNotice: true
          });
        }
        wx.stopPullDownRefresh();
      },
      fail: function(res) {
        console.log(res);
        wx.stopPullDownRefresh();
      }
    });

  },
  gofufei(){
    wx.navigateTo({
      url: '/packageD/article/PayarticleList/PayarticleList'
    });
  },
  toNoticeInfo(e) {
    let item = e.currentTarget.dataset.item;
    if (item.has_one_article_pay){
      if (item.has_one_record) {
        if(item.type == 1){
          if(this.data.options.taskID){
            wx.navigateTo({
              url: `/packageA/member/course/VoiceDetail/VoiceDetail?article_id=${item.id}&taskID=${this.data.options.taskID}&taskDay=${this.data.options.taskDay}`
            });
          }else{
            wx.navigateTo({
              url: '/packageA/member/course/VoiceDetail/VoiceDetail?article_id=' + item.id
            });
          }
        }else{
          if(this.data.options.taskID){
            wx.navigateTo({
              url: `/packageA/member/article/articleContent/articleContent?article_id=${item.id}&taskID=${this.data.options.taskID}&taskDay=${this.data.options.taskDay}`
            });
          }else{
            wx.navigateTo({
              url: '/packageA/member/article/articleContent/articleContent?article_id=' + item.id
            });
          }
        }
      }else{
        wx.navigateTo({
          url: '/packageD/article/articleList/articleList?article_id=' + item.id
        });
      }
    }else{
      if(item.type == 1){
        if(this.data.options.taskID){
          wx.navigateTo({
            url: `/packageA/member/course/VoiceDetail/VoiceDetail?article_id=${item.id}&taskID=${this.data.options.taskID}&taskDay=${this.data.options.taskDay}`
          });
        }else{
          wx.navigateTo({
            url: '/packageA/member/course/VoiceDetail/VoiceDetail?article_id=' + item.id
          });
        }
      }else{
        if(this.data.options.taskID){
          wx.navigateTo({
            url: `/packageA/member/article/articleContent/articleContent?article_id=${item.id}&taskID=${this.data.options.taskID}&taskDay=${this.data.options.taskDay}`
          });
        }else{
          wx.navigateTo({
            url: '/packageA/member/article/articleContent/articleContent?article_id=' + item.id
          });
        }
      }
    }
  },
  onClick(e) {
    let index = e.detail.index;
    this.initData();
    if (index === 0) {
      this.setData({
        id: ''
      });
    } else {
      this.setData({
        id: this.data.categories[index - 1].id
      });
    }
    this.getNetData();
  },
  getMoreData() {
    var that = this;
    if (this.data.page === this.data.total_page) {
      return;
    }
    if (this.data.page >= this.data.total_page) {
      that.setData({
        loading: true,
        allLoaded: true
      });
      return;
    } else {
      that.setData({
        page: this.data.page + 1
      });
      let json = {
        category_id: this.data.id,
        page: this.data.page,
        keyword: this.data.searchText
      };
      let urlStr = app.getNetAddresss("plugin.article.api.article.get-articles");
      app._getNetWork({
        url: urlStr,
        data: json,
        success: function(resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            that.setData({
              total_page: res.data.articles.last_page,
              loading: false,
              allLoaded: false,
              datas: that.data.datas.concat(res.data.articles.data)
            });
          } else {
            that.setData({
              page: that.data.page - 1,
              loading: true,
              allLoaded: true,
              isLoadMore: false
            });
          }
        },
        fail: function(res) {
          console.log(res);
        }
      });
    }
  }
});
